package com.csjbot.weedle_auto.adapter

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.view.ViewGroup
import com.csjbot.weedle_auto.fragment.AutomaticFramgent
import com.csjbot.weedle_auto.fragment.PrintFragment
import java.util.*

/**
 * Created by chenqi on 8/4/17.
 */

class MyFragmentAdapter(private val fm: FragmentManager, internal var list: List<Fragment>) : FragmentPagerAdapter(fm) {
    private val tagList: MutableList<String>


    init {
        tagList = ArrayList()
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        //        tagList.add(list.get(position).getTag());
        tagList.add(makeFragmentName(container.id, getItemId(position)))
        return super.instantiateItem(container, position)
    }


    /**
     * 根据Item的位置返回对应位置的Fragment，绑定item和Fragment
     * @param arg0
     * @return
     */
    override fun getItem(arg0: Int): Fragment {
        return list[arg0]
    }

    /**
     * 设置Item的数量
     * @return
     */
    override fun getCount(): Int {
        return list.size
    }


    fun update(item: Int) {
        val fragment = fm.findFragmentByTag(tagList[item])
        if (fragment != null) {
            when (item) {
                0 -> {
                }
                1 -> (fragment as AutomaticFramgent).update()
                2 -> (fragment as PrintFragment).update()
                else -> {
                }
            }
        }
    }


    private fun makeFragmentName(viewId: Int, id: Long): String {
        return "android:switcher:$viewId:$id"
    }
}
